package cn.lhf.cd;

import cn.lhf.cd.entity.User;
import cn.lhf.cd.mapper.UserMapper;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.util.Properties;

public class Main {
    private static DataSource dataSource;                   //数据源
    private static SqlSessionFactory sqlSessionFactory;     //sqlSession分发工厂

    /**
     * 初始化数据源
     */
    private static void initDataSource() throws Exception {
        Properties dbConfig = new Properties();
        InputStream dbConfigStream = Main.class.getResourceAsStream("/db-config.properties");   //打开配置文件流
        if (dbConfigStream == null)
            throw new Exception("未能载入数据库配置文件");
        dbConfig.load(dbConfigStream);  //加载配置
        dbConfigStream.close();         //关闭文件
        dataSource = DruidDataSourceFactory.createDataSource(dbConfig); //初始化数据源
    }

    /**
     * 初始化mybatis
     */
    private static void initSqlSessionFactory() {
        Environment environment = new Environment("development", new JdbcTransactionFactory(), dataSource); //环境，主要是事务管理和数据源实例
        Configuration configuration = new Configuration(environment);   //封装环境为置
        configuration.addMappers("cn.lhf.cd.mapper");       //Mapper的扫描位置

        sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);    //构建SqlSession分发工厂类实例
    }

    /**
     * 打开一个SQLSession
     * @return SQLSession
     */
    public static SqlSession openSqlSession() {
        return sqlSessionFactory.openSession();
    }

    /**
     * 生成用户
     * @param num 要生成的用户数量
     * @throws Exception 神奇的异常
     */
    private static void genUser(int num) throws Exception {
        SqlSession sqlSession = openSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        if (userMapper.count() < 1) {
            for (int i = 0; i < num; i++) {
                User user = new User();
                user.setPassword("123456");
                userMapper.add(user);
            }

            sqlSession.commit();
        }
        sqlSession.close();
    }

    public static void main(String[] args) {
        try {
            initDataSource();
            initSqlSessionFactory();
            genUser(10);        //如果没有用户就创建10个用户
            FXApplication.launch(FXApplication.class, args);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
